#include "areaconfig.h"
#include "ui_areaconfig.h"
#include <QDebug>
#include <QMessageBox>
#include <QFileDialog>
#include <QStandardPaths>


areaConfig::areaConfig(wThread *w,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::areaConfig)
{
    ui->setupUi(this);
    table_init();
    event_init();
    ment_init();
    channel_event_init();
    SelectRowID = -1;
    channels.clear();
    wTh = w;
//    wTh = new wThread();
    wTh->recvAreaTable(ui->areatable,headers);
    connect(wTh,SIGNAL(export_areachannel_ok()),this,SLOT(deal_export()));
}

areaConfig::~areaConfig()
{
    delete ui;
}

void areaConfig::deal_export()
{
    QMessageBox::warning(NULL, "prompt", "Export file finish!", "OK");
}

void areaConfig::table_init()
 {
    QString str = "No#AreaName#channelsize";
    headers = str.split("#");

    ui->areatable->setColumnCount(headers.size()); //设置列数
    ui->areatable->setHorizontalHeaderLabels(headers);

    for (int x = 0; x < headers.size(); x++)
        ui->areatable->horizontalHeader()->setSectionResizeMode(x,QHeaderView::ResizeToContents);

    ui->areatable->setSelectionBehavior(QAbstractItemView::SelectRows); //设置选择行为，以行为单位
    ui->areatable->setSelectionMode(QAbstractItemView::SingleSelection); //设置选择模式，选择单行

    QString str1 = "No#AreaNo#Channel Name#Channel Type#TX Frequency#RX Frequency#Color Code/Bandwidth#Power#Channel Mode/RX CTCSS Type#Call Type/RX CTCSS Code#Output Timeslot/TX CTCSS Type#Input Timeslot/TX CTCSS Code#Volume#Mute";
    headers2 = str1.split("#");

    ui->channeltable->setColumnCount(headers2.size()); //设置列数
    ui->channeltable->setHorizontalHeaderLabels(headers2);

    for (int x = 0; x < headers2.size(); x++)
        ui->channeltable->horizontalHeader()->setSectionResizeMode(x,QHeaderView::ResizeToContents);

 }


void areaConfig::event_init()
{
    ui->areatable->setContextMenuPolicy(Qt::CustomContextMenu);
    RightClick = new QMenu(ui->areatable);                        //点击菜单
    selectAction = new QAction(QString("Delect"),this);     //删除事件
    RightClick->addAction(selectAction);
    connect(ui->areatable,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(RightClickSlot(QPoint)));
    connect(ui->areatable,SIGNAL(clicked(const QModelIndex &)), this, SLOT(onTableClicked(const QModelIndex &)));
    connect(RightClick,SIGNAL(triggered(QAction*)),this,SLOT(RightClickDelete(QAction*)));
}

void areaConfig::channel_event_init()
{
    ui->channeltable->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    ui->channeltable->setContextMenuPolicy(Qt::CustomContextMenu);
    RightClickchannel = new QMenu(ui->channeltable);                        //点击菜单
    selectActionchannel = new QAction(QString("Delect"),this);     //删除事件
    RightClickchannel->addAction(selectActionchannel);
    connect(ui->channeltable,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(RightClickSlotchannel(QPoint)));
    connect(RightClickchannel,SIGNAL(triggered(QAction*)),this,SLOT(RightClickDeletechannel(QAction*)));
}

void areaConfig::ment_init()
{
    menuBar = new QMenuBar(this); //1.创建菜单栏

    fileMenu = new QMenu("File",this);   //2.创建菜单
    //3.创建行为(Action)
    QAction *fileExportAction = new QAction("Export Excel File",this);
    connect(fileExportAction,SIGNAL(triggered()),this,SLOT(exportFile()));

//    QAction *fileImportAction = new QAction("Import Excel File",this);
//    connect(fileImportAction,SIGNAL(triggered()),this,SLOT(importFile()));


    //4.将行为添加到菜单
    fileMenu->addAction(fileExportAction);
//    fileMenu->addAction(fileImportAction);

    menuBar->addMenu(fileMenu);

    menuBar->setGeometry(0,0,this->width(),30);
}

void areaConfig::exportFile()
{

    int row = ui->areatable->rowCount();
    if (row == 0) {
        QMessageBox::warning(NULL, "prompt", "There is no data!", "OK");
        return;
    }

    //把区域表和信道表导出
//    QString fileName = QFileDialog::getSaveFileName(this, tr("Save excel"),
//    ".", tr("Microsoft Office 2003 (*.xls)"));//获取保存路径
        QString fileName = QFileDialog::getSaveFileName(this, "保存",
                    QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),
                    "Excel 文件(*.xls *.xlsx)");
    if (fileName!="")
        {
            wTh->setExportAreaChannel();
            wTh->recvParaAreaChannel(ui->areatable,&channels, fileName);
            wTh->start();
        }

}

void areaConfig::RightClickSlotchannel(QPoint pos)
{
    QModelIndex index = ui->channeltable->indexAt(pos);    //找到tableview当前位置信息
    selectRowchannel = index.row();    //获取到了当前右键所选的行数
    if(index.isValid())        //如果行数有效，则显示菜单
    {
        RightClickchannel->exec(QCursor::pos());
    }

}

void areaConfig::onTableClicked(const QModelIndex &index)
{
    SelectRowID = ui->areatable->item(index.row(),0)->text().toInt();
    qDebug() << "SelectRowID = " <<SelectRowID;

    if (channels.keys().size() == 0) {
        return;
    }

    ui->channeltable->clear();
    ui->channeltable->setColumnCount(0);
    ui->channeltable->setRowCount(0);
    table_init();

    QMap<int,CHANNINFO>::iterator i;

    int row = 0;

    for(i = channels.begin(); i != channels.end(); ++i) {

        QStringList tmp = i.value().AreaID.split("#");
        QString aid = tmp.at(0);

        if (aid.toInt() != SelectRowID)
            continue;
        //qDebug() << "No" << tmp.at(1) << "AreaNo" <<tmp.at(0);
        QString str = tmp.at(1) + "#" + tmp.at(0) + "#"
                + i.value().ChannelName + "#" + i.value().ChannelType + "#"
                + i.value().TXFrequency + "#" + i.value().RXFrequency + "#"
                + i.value().ColorCode + "#" + i.value().Power + "#"
                + i.value().ChannelMode + "#" + i.value().CallType + "#"
                + i.value().OutputTimeslot + "#" + i.value().InputTimeslot + "#"
                + i.value().Volume + "#" + i.value().MicGain + "#";

        qDebug() <<str;
        QStringList list = str.split("#");

        ui->channeltable->insertRow(row);

        for (int j = 0; j < list.count()-1; j++) {
            //qDebug() << list.at(j);
            QTableWidgetItem *item = new QTableWidgetItem(list.at(j));
            ui->channeltable->setItem(row, j, item);
        }
        row++;
    }

}

void areaConfig::onClick(QAction *act)
{

}

void areaConfig::RightClickSlot(QPoint pos)
{
    QModelIndex index = ui->areatable->indexAt(pos);    //找到tableview当前位置信息
    iselectcRow = index.row();    //获取到了当前右键所选的行数

    if(index.isValid())        //如果行数有效，则显示菜单
    {
        RightClick->exec(QCursor::pos());
    }
}

void areaConfig::update_channel(int aid,int cid)
{

    QString str = QString("%1#%2#").arg(aid).arg(cid);

    QMap<int,CHANNINFO>::iterator  i;
    for(i = channels.begin(); i != channels.end();) {
        if (str == i.value().AreaID) {
            i = channels.erase(i);
            break;
        }
        else {
            i++;
        }
    }

    channelsTemp.clear();

    for(i = channels.begin(); i != channels.end();) {
        channelsTemp.insert(channelsTemp.keys().size(),i.value());
        i++;
    }

    channels.clear();
    channels = channelsTemp;

}

void areaConfig::RightClickDeletechannel(QAction *act)
{
    QMessageBox message(QMessageBox::NoIcon, QString("prompt"),
                                QString("Do you choose the bank data?"),
    QMessageBox::Yes | QMessageBox::No, NULL);

    if(message.exec() == QMessageBox::Yes)
    {
        if(act->text() == QString("Delect"))   //看选中了删除这个菜单
        {
            int aid = ui->channeltable->item(selectRowchannel,1)->text().toInt();
            int cid = ui->channeltable->item(selectRowchannel,0)->text().toInt();
            //update_channel(aid,cid);
            ui->channeltable->removeRow(selectRowchannel);  //删除掉了表格信息

            update_table(selectRowchannel);
            Updatechannels(aid);

        }
    }
}

void areaConfig::update_table(int row)
{
    qDebug() << "删除的是第几行----" << row;

    int col = ui->channeltable->columnCount();
    //总共多少行
    int rowcount = ui->channeltable->rowCount();
    qDebug() << "rowcount = " << rowcount;


    //更新表格
    for (int i = row; i < rowcount; i++) {
        int id;
        if (i == 0) {
            id = 1;
        }
        else {
            id = ui->channeltable->item(i-1,0)->text().toInt();
            id += 1;
        }
        QString value = QString("%1").arg(id);
        QTableWidgetItem *item = new QTableWidgetItem(value);
        ui->channeltable->setItem(i, 0, item);



        QString str = ui->channeltable->item(i,2)->text();//取出字符串
        if (str.contains("Channel",Qt::CaseSensitive)) {
            value = QString("Channel%1").arg(id);
            QTableWidgetItem *item = new QTableWidgetItem(value);
            ui->channeltable->setItem(i, 2, item);
        }

    }

     col = ui->channeltable->columnCount();
    //总共多少行
     rowcount = ui->channeltable->rowCount();
     qDebug() <<"更新表格之后多少行" <<rowcount;

     //更新MAP
     QMap<int,CHANNINFO>::iterator  i;
     for(i = channels.begin(); i != channels.end();) {
         QStringList tmp = i.value().AreaID.split("#");
         QString aid = tmp.at(0);
         qDebug()<<"aid.toInt()"<<aid.toInt()<< " == " <<"SelectRowID"<<SelectRowID;
         if (aid.toInt() == (SelectRowID)) {
             i = channels.erase(i);
         }
         else {
             i++;
         }
     }

     channelsTemp.clear();

     for(i = channels.begin(); i != channels.end();) {
         channelsTemp.insert(channelsTemp.keys().size(),i.value());
         i++;
     }

     for (int i = 0; i < rowcount; i++) {
            CHANNINFO chaninfo;
            chaninfo.AreaID = QString("%1#%2#").arg(ui->channeltable->item(i,1)->text()).
                    arg(ui->channeltable->item(i,0)->text());
             chaninfo.ChannelName = ui->channeltable->item(i,2)->text();
             chaninfo.ChannelType = ui->channeltable->item(i,3)->text();
             chaninfo.TXFrequency = ui->channeltable->item(i,4)->text();
             chaninfo.RXFrequency = ui->channeltable->item(i,5)->text();
             chaninfo.ColorCode = ui->channeltable->item(i,6)->text();
             chaninfo.Power = ui->channeltable->item(i,7)->text();
             chaninfo.ChannelMode = ui->channeltable->item(i,8)->text();
             chaninfo.CallType = ui->channeltable->item(i,9)->text();
             chaninfo.OutputTimeslot = ui->channeltable->item(i,10)->text();
             chaninfo.InputTimeslot = ui->channeltable->item(i,11)->text();
             chaninfo.Volume = ui->channeltable->item(i,12)->text();
             chaninfo.MicGain = ui->channeltable->item(i,13)->text();
            channelsTemp.insert(channelsTemp.keys().size(),chaninfo);
     }


    channels.clear();
    channels = channelsTemp;
    Updatechannels(SelectRowID);
}


void areaConfig::RightClickDelete(QAction *act)
{
    QMessageBox message(QMessageBox::NoIcon, QString("prompt"),
                                QString("Do you choose the bank data?"),
    QMessageBox::Yes | QMessageBox::No, NULL);

    if(message.exec() == QMessageBox::Yes)
    {
        if(act->text() == QString("Delect"))   //看选中了删除这个菜单
        {
            QMap<int,CHANNINFO>::iterator  i;
            for(i = channels.begin(); i != channels.end();) {
                QStringList tmp = i.value().AreaID.split("#");
                QString aid = tmp.at(0);
                if (aid.toInt() == (iselectcRow + 1)) {
                    qDebug() <<"删除ID" <<aid.toInt();
                    i = channels.erase(i);
                }
                else {
                    i++;
                }
            }

            channelsTemp.clear();

            for(i = channels.begin(); i != channels.end();) {
                QStringList tmp = i.value().AreaID.split("#");
                QString aid = tmp.at(0);
                //qDebug() << "---" <<aid.toInt() << "---" <<iselectcRow + 1;
                if (aid.toInt() > (iselectcRow + 1)) {
                    int a = aid.toInt() - 1;
                    QString str = QString("%1#%2#").arg(a).arg(tmp.at(1));
                    i.value().AreaID = str;
                    //channelsTemp.insert(channelsTemp.keys().size(),i.value());
                }
                channelsTemp.insert(channelsTemp.keys().size(),i.value());
                i++;
            }

            channels.clear();
            channels = channelsTemp;


            qDebug() << "iselectcRow = "<<iselectcRow;
            ui->areatable->removeRow(iselectcRow);  //删除掉了表格信息
            update_areatable();

            qDebug() << "删除后";
            for(i = channels.begin(); i != channels.end();++i) {
                qDebug() <<i.key() <<"---" <<i.value().AreaID;
            }

            ui->channeltable->clear();
            ui->channeltable->setColumnCount(0);
            ui->channeltable->setRowCount(0);
            table_init();

        }
    }
}

void areaConfig::update_areatable()
{
    qDebug() << "删除的是第几行" << iselectcRow;

    int col = ui->areatable->columnCount();
    //总共多少行
    int rowcount = ui->areatable->rowCount();
    qDebug() << "rowcount = " << rowcount;


    for (int i = iselectcRow; i < rowcount; i++) {
        int id;
        if (i == 0) {
            id = 1;
        }
        else {
            id = ui->areatable->item(i-1,0)->text().toInt();
            id += 1;
        }

        QString value = QString("%1").arg(id);
        QTableWidgetItem *item = new QTableWidgetItem(value);
        ui->areatable->setItem(i, 0, item);
        item->setFlags(item->flags() & (~Qt::ItemIsEditable));

        QString str = ui->areatable->item(i,1)->text();//取出字符串
        if (str.contains("Area",Qt::CaseSensitive)) {
            value = QString("Area%1").arg(id);
            QTableWidgetItem *item = new QTableWidgetItem(value);
            ui->areatable->setItem(i, 1, item);
        }
    }
}

void areaConfig::on_add_clicked()
{
    int col = ui->areatable->columnCount();
    int row = ui->areatable->rowCount();

     QString str;
    int id;

    if (row == 0) {
        id = 1;
    } else {
        id = ui->areatable->item(row-1,0)->text().toInt() + 1;
    }

    str += QString("%1#").arg(id);

    //str += "CH Name#";
    str += QString("Area%1#").arg(id);

    int size = 0;
    str += QString("%1#").arg(size);


    ui->areatable->insertRow(row);

    QStringList list = str.split("#");
    for (int i = 0; i < list.count()-1; i++) {
        QTableWidgetItem *item = new QTableWidgetItem(list.at(i));
        if (i == 0 || i == 2)
            item->setFlags(item->flags() & (~Qt::ItemIsEditable));
        ui->areatable->setItem(row, i, item);
    }
}



void areaConfig::on_clean_clicked()
{
    ui->areatable->clear();
    ui->areatable->setColumnCount(0);
    ui->areatable->setRowCount(0);

    ui->channeltable->clear();
    ui->channeltable->setColumnCount(0);
    ui->channeltable->setRowCount(0);
    table_init();

    channels.clear();
    SelectRowID = -1;
}

void areaConfig::on_addA_clicked()
{
    if (SelectRowID == -1)
        return;

    int col = ui->channeltable->columnCount();
    int row = ui->channeltable->rowCount();

    CHANNINFO chanelinfo;
    QString str;
        int id;

       if (row == 0) {
           id = 1;
       } else {
           //qDebug() << "id = " <<ui->channeltable->item(row-1,0)->text();//取出字符串
           id = ui->channeltable->item(row-1,0)->text().toInt() + 1;
       }

       str += QString("%1#").arg(id);

       str += QString("%1#").arg(SelectRowID);

       str += QString("Channel%1#").arg(id);
       chanelinfo.ChannelName = QString("Channel%1").arg(id);

       QString type = "A";
        str += type + "#";
        chanelinfo.ChannelType = "A";

        QString tx = "401.02500";
        str += tx + "#";
        chanelinfo.TXFrequency = "401.02500";

        QString rx = "401.02500";
        str += rx + "#";
         chanelinfo.RXFrequency = "401.02500";

        QString Bandwidth = "2";
        str += Bandwidth + "#";
        chanelinfo.ColorCode = "2";

        QString power = "1";
        str += power + "#";
         chanelinfo.Power = "1";

        QString RX_CTCSS_Type = "1";
        str += RX_CTCSS_Type + "#";
        chanelinfo.ChannelMode = "1";

        QString RX_CTCSS_Code = "0";
        str += RX_CTCSS_Code + "#";
        chanelinfo.CallType = "0";

        QString TX_CTCSS_Type = "1";
        str += TX_CTCSS_Type + "#";
        chanelinfo.OutputTimeslot = "1";

        QString TX_CTCSS_Code = "0";
        str += TX_CTCSS_Code + "#";
        chanelinfo.InputTimeslot = "0";

        QString volume = "6";
        str += volume + "#";
        chanelinfo.Volume = "6";

        QString gain = "4";
        str += gain + "#";
        chanelinfo.MicGain = "4";
        qDebug() << "+++" <<str;

        ui->channeltable->insertRow(row);

        QStringList list = str.split("#");

        QString sId = QString("%1#%2#").arg(SelectRowID).arg(id);
        chanelinfo.AreaID = sId;
        channels.insert(channels.keys().size(),chanelinfo);


        for (int i = 0; i < col; i++) {
            QTableWidgetItem *item = new QTableWidgetItem(list.at(i));
            ui->channeltable->setItem(row, i, item);
            //ui->tableWidget->item(row,i)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        }
        Updatechannels(SelectRowID);
}

void areaConfig::Updatechannels(int row)
{
    qDebug() << "row = " << row;
    QMap<int,CHANNINFO>::iterator  i;
    int num = 0;

    for(i = channels.begin(); i != channels.end();) {
        QStringList tmp = i.value().AreaID.split("#");
        QString aid = tmp.at(0);
        if (aid.toInt() == (row)) {
            num++;
        }
        i++;
    }

    qDebug() << "num = " <<num;

    //QString str = ui->areatable->item(SelectRowID-1,2)->text();//取出字符串
    QTableWidgetItem *item = new QTableWidgetItem(QString("%1").arg(num));
    item->setFlags(item->flags() & (~Qt::ItemIsEditable));
    ui->areatable->setItem(row-1, 2, item);

}

void areaConfig::on_addD_clicked()
{
    if (SelectRowID == -1)
        return;

    int col = ui->channeltable->columnCount();
    int row = ui->channeltable->rowCount();

    //qDebug() << "col = " << col << "row = " << row;

    CHANNINFO chanelinfo;
    //chanelinfo.AreaID = SelectRowID;

    QString str;
    int id;

    if (row == 0) {
        id = 1;
    } else {
        //qDebug() << "id = " <<ui->channeltable->item(row-1,0)->text();//取出字符串
        id = ui->channeltable->item(row-1,0)->text().toInt() + 1;
    }

    str += QString("%1#").arg(id);

    str += QString("%1#").arg(SelectRowID);
    //str += "CH Name#";
    str += QString("Channel%1#").arg(id);
    chanelinfo.ChannelName = QString("Channel%1").arg(id);

    QString type = "D";
    str += type + "#";
    chanelinfo.ChannelType = "D";

    QString tx = "401.02500";
    str += tx + "#";
    chanelinfo.TXFrequency = "401.02500";

    QString rx = "401.02500";
    str += rx + "#";
    chanelinfo.RXFrequency = "401.02500";

    QString color = "0";
    str += color + "#";
    chanelinfo.ColorCode = "0";

    QString power = "1";
    str += power + "#";
    chanelinfo.Power = "1";

    QString channel_mode = "1";
    str += channel_mode + "#";
    chanelinfo.ChannelMode = "1";

    QString call_type = "2";
    str += call_type + "#";
    chanelinfo.CallType = "2";

    QString output_time = "1";
    str += output_time + "#";
    chanelinfo.OutputTimeslot = "1";

    QString input_time = "1";
    str += input_time + "#";
    chanelinfo.InputTimeslot = "1";

    QString volume = "6";
    str += volume + "#";
    chanelinfo.Volume = "6";

    QString gain = "4";
    str += gain + "#";
    chanelinfo.MicGain = "4";

    ui->channeltable->insertRow(row);

    QStringList list = str.split("#");

    QString sId = QString("%1#%2#").arg(SelectRowID).arg(id);
    chanelinfo.AreaID = sId;
    channels.insert(channels.keys().size(),chanelinfo);

    //qDebug() << "AreaID = " << chanelinfo.AreaID;
    //qDebug() << "str = " <<str;

    for (int i = 0; i < list.count()-1; i++) {
        //qDebug() << list.at(i);
        QTableWidgetItem *item = new QTableWidgetItem(list.at(i));
        ui->channeltable->setItem(row, i, item);
    }
    Updatechannels(SelectRowID);

}

void areaConfig::on_Clean_clicked()
{

    //qDebug() << "SelectRowID = " <<SelectRowID ;
    //总共多少行
    int rowcount = ui->channeltable->rowCount();

    if (rowcount == 0)
        return;

    ui->channeltable->clear();
    ui->channeltable->setColumnCount(0);
    ui->channeltable->setRowCount(0);
    table_init();

    QMap<int,CHANNINFO>::iterator  i;
    for(i = channels.begin(); i != channels.end();) {
        QStringList tmp = i.value().AreaID.split("#");
        QString aid = tmp.at(0);
        if (aid.toInt() == (SelectRowID)) {
            i = channels.erase(i);
        }
        else {
            i++;
        }
    }

    channelsTemp.clear();

    for(i = channels.begin(); i != channels.end();) {
        QStringList tmp = i.value().AreaID.split("#");
        QString aid = tmp.at(0);
        if (aid.toInt() > (SelectRowID)) {
            int a = aid.toInt() - 1;
            QString str = QString("%1#%2#").arg(a).arg(tmp.at(1));
            i.value().AreaID = str;
        }
        channelsTemp.insert(channelsTemp.keys().size(),i.value());
        i++;
    }

    channels.clear();
    channels = channelsTemp;
    Updatechannels(SelectRowID);
}
